package com.lhj.security.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lhj.security.constants.Constants;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author lhj
 * @Date 2024/12/27 16:48
 */
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding(Constants.UTF8);
        response.setContentType("application/json; utf-8");

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", HttpStatus.UNAUTHORIZED.value());
        resultMap.put("info", HttpStatus.UNAUTHORIZED.getReasonPhrase());
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(resultMap));
        writer.flush();
    }
}
